package com.jzo2o.foundations.handler;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.model.dto.response.ServeAggregationSimpleResDTO;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class SpringCacheSyncHandler {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IRegionService regionService;
    @Autowired
    private IServeService serveService;

    @XxlJob("activeRegionCacheSync")
    public void activeRegionCacheSync() {
        log.info("开始同步已开通服务区域缓存");
        //删除缓存
        redisTemplate.delete(RedisConstants.CacheName.JZ_CACHE + "::ACTIVE_REGIONS");
        //同步最新的缓存
        //查询所有已启用区域
        List<RegionSimpleResDTO> dtos = regionService.queryActiveRegionListCache();
        //遍历每个区域
        dtos.forEach(e -> {
            //删除每个区域的首页服务的数据
            redisTemplate.delete(RedisConstants.CacheName.SERVE_ICON + "::" + e.getId());
            serveService.indexServeList(e.getId());
        });
        //缓存同步首页服务列表
        log.info("同步已开通服务区域缓存完成");

    }

    @XxlJob(("hotServeCacheSync"))
    public void hotServeCache() {
        log.info("开始同步热点服务缓存");
        //查询所有已启用区域
        List<RegionSimpleResDTO> dtos = regionService.queryActiveRegionListCache();
        dtos.forEach(e -> {
            //每个区域的热门项目都进行删除
            redisTemplate.delete(RedisConstants.CacheName.HOT_SERVE + "::" + e.getId());
            serveService.hotServeList(e.getId());
        });
        //缓存同步首页服务列表
        log.info("同步热点服务缓存已完成");
    }

    @XxlJob(("hotServeInfoCacheSync"))
    public void hotServeInfoCache() {
        log.info("开始同步热点服务详情缓存");
        //查询所有已启用区域
        List<RegionSimpleResDTO> dtos = regionService.queryActiveRegionListCache();
        dtos.forEach(e -> {
            //查询该区域下的所有热点服务
            List<ServeAggregationSimpleResDTO> list = serveService.hotServeList(e.getId());
            if (CollUtils.isNotEmpty(list)) {
                list.forEach(item -> {
                    redisTemplate.delete(RedisConstants.CacheName.SERVE + "::" + item.getId());
                    serveService.findHotServeInfoById(item.getId());
                });
            }
        });
        //缓存同步首页服务列表
        log.info("同步热点服务详情缓存已完成");
    }
}
